package com.bsgogogo.common.config;

import com.bsgogogo.entity.Account;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 定义一个拦截器
 */
public class MyInterceptor implements HandlerInterceptor {

    //在调用所有处理请求的方法之前被自动调用执行的方法

    /**
     * 监测全局session对象中是否有user数据，如果有则放行，如果没有重定向到登录页面
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 处理器(url+Controller：映射)
     * @return 如果返回值为true，表示放行当前的请求；如果返回值为false，表示拦截当前的请求
     * @throws Exception
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse
            response, Object handler) throws Exception {
        Account user = (Account) request.getSession().getAttribute("user");
        if (user == null) {
            // 重定向到登录页
            response.sendRedirect("/end/page/login.html");
            return false;
        }
        //放行请求
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse
            response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse
            response, Object handler, Exception ex) throws Exception {
    }
}
